/**
 * Bluetooth AutoAnswer Program
 * @author punan
 * @time 2013.02.20
 */


package com.huaqin.punan.buleautoanswer;

import java.lang.reflect.Method;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothHeadset;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
//import android.os.RemoteException;
import android.util.Log;

//import com.android.internal.telephony.ITelephony;

public class BluetoothAutoAnswerService extends Service {
	public static final String TAG = "BluetoothAutoAnswerService";
	private TelephonyManager mTelephonyManager;
	private BroadcastReceiver mBluetoothHeadsetReceiver;
	
	public static int delaySeconds = 1;
	private boolean isConnected = false;
	private boolean debugFlag = true;

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		if(debugFlag)
			Log.i(TAG, "===>>onCreate()");
		
		super.onCreate();
		
		isConnected = isBluetoothConnected();
		
		mTelephonyManager = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
		mTelephonyManager.listen(new MyPhoneStateListener(),PhoneStateListener.LISTEN_CALL_STATE);
		
        mBluetoothHeadsetReceiver = new BluetoothHeadsetReceiver();
        registerReceiver(mBluetoothHeadsetReceiver,new IntentFilter(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED));
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		if(debugFlag)
			Log.i(TAG, "===>>onStartCommand(), isConnected="+isConnected);
		
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		if(debugFlag)
			Log.i(TAG, "===>>onDestroy()");
		
		super.onDestroy();
		mTelephonyManager = null;
		unregisterReceiver(mBluetoothHeadsetReceiver);
	}

	private boolean isBluetoothConnected(){
		boolean bluetoothConnected = false;
		try {
			bluetoothConnected = 
					BluetoothAdapter.
					getDefaultAdapter().
					getProfileConnectionState(android.bluetooth.BluetoothProfile.HEADSET) 
					!= android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
		}catch(Exception e){
			bluetoothConnected = false;
			e.printStackTrace();
		}
		return bluetoothConnected;
	}
	
	class MyPhoneStateListener extends PhoneStateListener {
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			// TODO Auto-generated method stub
			switch (state) {
			case TelephonyManager.CALL_STATE_IDLE:
				if(debugFlag)
					Log.i(TAG, "===>>CALL_STATE_IDLE");

				break;

			case TelephonyManager.CALL_STATE_RINGING:
				if(debugFlag)
					Log.i(TAG, "===>>CALL_STATE_RINGING");
				if(isConnected){
					try {
						Thread.sleep(1000*delaySeconds);

						Class c = Class.forName(mTelephonyManager.getClass().getName());
						Method m = null;
						m = c.getDeclaredMethod("getITelephony");
						m.setAccessible(true);

						if(debugFlag)
							Log.i(TAG, "==>>>Bluetooth Headset Connected, Answer the call now...");
							
						// ITelephony telephonyService = (ITelephony)
						// m.invoke(mTelephonyManager);

						// iTelephony.endCall();//结束通话
						// iTelephony.silenceRinger();//不响铃
						// iTelephony.answerRingingCall();//接听

						// telephonyService.answerRingingCall();

					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (NoSuchMethodException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					// }catch (RemoteException e) {
						// TODO Auto-generated catch block
						// e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}else{
					if(debugFlag)
						Log.i(TAG, "==>>>Bluetooth HeadSet Not Connected!!");
				}
				break;

			case TelephonyManager.CALL_STATE_OFFHOOK:
				if(debugFlag)
					Log.i(TAG, "===>>CALL_STATE_OFFHOOK");
				break;
			}

			super.onCallStateChanged(state, incomingNumber);
		}
	}
	
	
	//Broadcastreceiver
	class BluetoothHeadsetReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			
			if(debugFlag)
				Log.i(TAG, "BluetoothHeadsetReceiver onReceive");
			
			try {
				String action = intent.getAction();

				if (action == null)
					return;
				
				if(debugFlag)
					Log.e(TAG, "BluetoothHeadsetReceiver action="+action);
					
				int extraData = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE,BluetoothHeadset.STATE_AUDIO_DISCONNECTED);
				if (extraData == BluetoothHeadset.STATE_CONNECTED) {
						
					if(debugFlag)
						Log.i(TAG, "==>>STATE_CONNECTED");
					isConnected = true;
				} else if (extraData == BluetoothHeadset.STATE_DISCONNECTED) {
						
					if(debugFlag)
						Log.i(TAG, "==>>STATE_DISCONNECTED");
					isConnected = false;
				}else{
					if(debugFlag)
						Log.i(TAG, "==>>OTHER_STATE:"+extraData);
				}
			} catch (Exception e) {
				
				e.printStackTrace();
			}
		}
	}
	
}
